package com.nbsaas.boot.utils.file;

import java.io.InputStream;
import java.security.MessageDigest;

public class FileHashUtils {

    public static String calculateHash(InputStream inputStream, String algorithm) throws Exception {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        byte[] buffer = new byte[8192]; // 8KB 缓冲区，避免内存占用过大
        int read;
        while ((read = inputStream.read(buffer)) != -1) {
            digest.update(buffer, 0, read);
        }
        byte[] hash = digest.digest();
        // 转为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    public static String md5(InputStream inputStream) throws Exception {
        return calculateHash(inputStream, "MD5");
    }

    public static String sha256(InputStream inputStream) throws Exception {
        return calculateHash(inputStream, "SHA-256");
    }
}
